﻿using MediatR;
using RBAC_Uthorization.API.Application.Command.UserInfoCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Interface;

namespace RBAC_Uthorization.API.Application.CommandHandlers.UserInfoHandler
{
    public class USerInfoDeleteCommandHandlers : IRequestHandler<USerInfoDeleteCommand, ApiResult<int>>
    {
        private readonly IUserInfoRepository _userInfoRepository;
        private readonly ILogger<USerInfoDeleteCommandHandlers> _logger;

        public USerInfoDeleteCommandHandlers(ILogger<USerInfoDeleteCommandHandlers> logger, IUserInfoRepository userInfoRepository)
        {
            _logger = logger;
            _userInfoRepository = userInfoRepository;
        }

        public async Task<ApiResult<int>> Handle(USerInfoDeleteCommand request, CancellationToken cancellationToken)
        {
           
            try
            {
                foreach (var item in request.id)
                {
                    var datalist = await _userInfoRepository.GetAllAsunc(x=>x.id==item&&x.del_flag==0&&x.offic_id==request.office_id&&x.sys_id==request.sys_id);
                     var data= datalist.FirstOrDefault();
                    if (data == null)
                    {
                        return new ApiResult<int>
                        {
                            Code = ResultCode.Fail,
                            Message = "用户信息不存在"
                        };
                    }
                    data.del_flag = 1;
                    data.update_by = request.Createby;
                    data.update_date = DateTime.UtcNow;
                    var result = await _userInfoRepository.UpdateAsync(data);
                }
               
                _logger.LogInformation($"删除用户信息成功:{request.id}");
                return new ApiResult<int>();

            }
            catch (Exception e)
            {
                _logger.LogError($"删除用户信息失败:{e.Message}->{e.StackTrace}->{e.InnerException}");
                return new ApiResult<int>
                {
                    Code=ResultCode.Fail,
                    Message = "删除用户信息失败"
                };
            }
           
        }
    }
}
